//
//  YYELoginViewController.m
//  YuYingEDU
//
//  Created by 胡波 on 2017/12/30.
//  Copyright © 2017年 胡波. All rights reserved.
//

#import "YYELoginViewController.h"
#import "JKCountDownButton.h"
#import "YYEBindPhoneViewController.h"
#import "YYEMoreInfoViewController.h"
#import <UMSocialCore/UMSocialCore.h>
#import "RegexTool.h"

#define kCountDownForVerifyCode @"CountDownForVerifyCode"


@interface YYELoginViewController ()

@property (nonatomic,strong) UITextField *phoneTF;
@property (nonatomic,strong) UITextField *veriTF;
@property (nonatomic,strong) UIButton *loginBtn;
@property (nonatomic,strong) UIButton *wechatBtn;
@property (nonatomic,strong) UIButton *qqBtn;
@property (nonatomic, strong) UIButton *countDownButton;

@end

@implementation YYELoginViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"登录";
    
    [self configUI];
    
}

- (void)configUI {
    
    self.phoneTF = [[UITextField alloc]init];
    self.phoneTF.placeholder = @"请输入您的手机号码";
    [self.view addSubview:self.phoneTF];
    self.phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    
    UIView *phoneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 43, 38)];
    self.phoneTF.leftView = phoneView;
    self.phoneTF.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView *phoneIV = [[UIImageView alloc]initWithFrame:CGRectMake(10, 9.5, 13, 19)];
    phoneIV.image = [UIImage imageNamed:@"phone"];
    [phoneView addSubview:phoneIV];
    
    JKCountDownButton *veriBtn = [[JKCountDownButton alloc]init];
    [veriBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    [veriBtn setBackgroundColor:VeriBackColor];
    veriBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    veriBtn.layer.cornerRadius = 5;
    [self.view addSubview:veriBtn];
    self.countDownButton = veriBtn;
    [self.countDownButton addTarget:self action:@selector(getCodeAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.veriTF = [[UITextField alloc]init];
    self.veriTF.placeholder = @"请输入您收到的验证码";
    [self.view addSubview:self.veriTF];
    self.veriTF.keyboardType = UIKeyboardTypeNumberPad;

    
    UIView *veriView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 43, 38)];
    self.veriTF.leftView = veriView;
    self.veriTF.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView *veriIV = [[UIImageView alloc]initWithFrame:CGRectMake(8, 9.5, 17, 19)];
    veriIV.image = [UIImage imageNamed:@"password"];
    [veriView addSubview:veriIV];
    
    UIView *line1 = [[UIView alloc]init];
    line1.backgroundColor = LightLineColor;
    [self.view addSubview:line1];
    
    UIView *line2 = [[UIView alloc]init];
    line2.backgroundColor = LightLineColor;
    [self.view addSubview:line2];
    
    self.loginBtn = [[UIButton alloc]init];
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.loginBtn setBackgroundColor:GeneralBlueColor];
    self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    self.loginBtn.layer.cornerRadius = 5;
    [self.loginBtn addTarget:self action:@selector(loginClicked) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.loginBtn];
    
    self.wechatBtn = [[UIButton alloc]init];
    [self.wechatBtn setBackgroundImage:[UIImage imageNamed:@"wechat"] forState:UIControlStateNormal];
    [self.view addSubview:self.wechatBtn];
    [self.wechatBtn addTarget:self action:@selector(thirdpartLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    self.wechatBtn.tag = 0;
    
    self.qqBtn = [[UIButton alloc]init];
    [self.qqBtn setBackgroundImage:[UIImage imageNamed:@"QQ"] forState:UIControlStateNormal];
    [self.view addSubview:self.qqBtn];
    [self.qqBtn addTarget:self action:@selector(thirdpartLoginAction:) forControlEvents:UIControlEventTouchUpInside];
    self.qqBtn.tag = 1;
    
    UIView *leftLine = [[UIView alloc]init];
    leftLine.backgroundColor = LineColor;
    [self.view addSubview:leftLine];
    
    UIView *rightView = [[UIView alloc]init];
    rightView.backgroundColor = LineColor;
    [self.view addSubview:rightView];
    
    UILabel *cenLabel = [[UILabel alloc]init];
    cenLabel.text = @"OR";
    cenLabel.font = [UIFont systemFontOfSize:12];
    cenLabel.textAlignment = NSTextAlignmentCenter;
    cenLabel.textColor = GeneralBlueColor;
    [self.view addSubview:cenLabel];
    
    [self.phoneTF makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-130);
        make.top.equalTo(self.view.top).offset(20);
        make.height.equalTo(38);
    }];
    
    [line1 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-30);
        make.top.equalTo(self.phoneTF.bottom).offset(10);
        make.height.equalTo(0.5);
    }];
    
    [veriBtn makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.right).offset(-30);
        make.centerY.equalTo(self.phoneTF.centerY);
        make.size.equalTo(CGSizeMake(90, 26));
    }];
    
    [self.veriTF makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-30);
        make.top.equalTo(self.phoneTF.bottom).offset(20);
        make.height.equalTo(38);
    }];
    
    [line2 makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-30);
        make.top.equalTo(self.veriTF.bottom).offset(10);
        make.height.equalTo(0.5);
    }];
    
    [self.loginBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(30);
        make.right.equalTo(self.view.right).offset(-30);
        make.centerY.equalTo(self.view.centerY);
        make.height.equalTo(42);
    }];
    
    [self.wechatBtn makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.bottom).offset(-44);
        make.right.equalTo(self.view.centerX).offset(-30);
        make.size.equalTo(CGSizeMake(40, 40));
    }];
 
    [self.qqBtn makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.centerX).offset(30);
        make.bottom.equalTo(self.view.bottom).offset(-44);
        make.size.equalTo(CGSizeMake(40, 40));
    }];
    
    [cenLabel makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.wechatBtn.top).offset(-23);
        make.centerX.equalTo(self.view.centerX);
        make.size.equalTo(CGSizeMake(30, 30));
    }];
    
    [leftLine makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.left).offset(47);
        make.right.equalTo(cenLabel.left).offset(-11);
        make.centerY.equalTo(cenLabel.centerY);
        make.height.equalTo(0.5);
    }];
    
    [rightView makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.right).offset(-47);
        make.left.equalTo(cenLabel.right).offset(11);
        make.centerY.equalTo(cenLabel.centerY);
        make.height.equalTo(0.5);
    }];
    
    //倒计时通知事件
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(countDownUpdate:) name:@"CountDownUpdate" object:nil];
    
}

- (void)getCodeAction
{
    [self.view endEditing:YES];
    
    if (![RegexTool checkPhone:self.phoneTF.text]) {
        [self.view makeToast:@"无效的手机号"];
        return;
    }
    
    // 开始计时
    [CountDownServer startCountDown:60 identifier:kCountDownForVerifyCode];
    
    
    NSDictionary *dic = @{
                          @"username":self.phoneTF.text
                          };
    [SVProgressHUD show];
    [AFNHelper post:SendSms parameters:dic success:^(id responseObject) {
        
        //        NSLog(@"%@",responseObject);
        if ([responseObject[@"status"] isEqual:@1]) {
            

        }
        [SVProgressHUD showWithStatus:responseObject[@"message"]];
        [SVProgressHUD dismissWithDelay:1];
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        [SVProgressHUD dismiss];
        
    }];

    
}

- (void)thirdpartLoginAction:(UIButton *)btn
{
    if (btn.tag == 0) {
        [self getUserInfoForPlatform:UMSocialPlatformType_WechatSession];
        
    }
    if (btn.tag == 1) {
        
        [self getUserInfoForPlatform:UMSocialPlatformType_QQ];

     }
}


- (void)getUserInfoForPlatform:(UMSocialPlatformType)platformType
{
    [[UMSocialManager defaultManager] getUserInfoWithPlatform:platformType currentViewController:self completion:^(id result, NSError *error) {
        
        UMSocialUserInfoResponse *resp = result;
        
        // 第三方登录数据(为空表示平台未提供)
        // 授权数据
        NSLog(@" uid: %@", resp.uid);
        NSLog(@" openid: %@", resp.openid);
        NSLog(@" accessToken: %@", resp.accessToken);
        NSLog(@" refreshToken: %@", resp.refreshToken);
        NSLog(@" expiration: %@", resp.expiration);
        
        // 用户数据
        NSLog(@" name: %@", resp.name);
        NSLog(@" iconurl: %@", resp.iconurl);
        NSLog(@" gender: %@", resp.unionGender);
        
        // 第三方平台SDK原始数据
        NSLog(@" originalResponse: %@", resp.originalResponse);
        
        NSMutableDictionary  *paramDic=[[NSMutableDictionary  alloc]initWithCapacity:0];
        
        if (platformType == UMSocialPlatformType_QQ) {
            [paramDic  setValue:@"qq" forKey:@"type"];
            
        }
        else {
            [paramDic  setValue:@"weixin" forKey:@"type"];
        }
        [paramDic  setValue:resp.openid forKey:@"openid"];

//        [paramDic  setValue:[InfoCache unarchiveObjectWithFile:@"pushToken"] forKey:@"deviceToken"];
//        [paramDic  setValue:@"ios" forKey:@"deviceType"];
        
        
        [SVProgressHUD show];
        [AFNHelper post:ThirdLogin parameters:paramDic success:^(id responseObject) {
            
            if ([responseObject[@"status"] isEqual:@0]) { // 注册/登录失败
                
                NSLog(@"登录失败");
                
            }else if ([responseObject[@"status"] isEqual:@1]) { // 登录成功
                
                PersonModel *model = [PersonModel yy_modelWithJSON:responseObject[@"data"][@"userinfo"]];
                [InfoCache archiveObject:model toFile:Person];
                
                [LoginModel shareLogin].token = responseObject[@"data"][@"token"];
                SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"token"], @"token");
                
                [LoginModel shareLogin].role = responseObject[@"data"][@"userinfo"][@"role_id"];
                SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"role_id"], @"role");
                
                [LoginModel shareLogin].uid = responseObject[@"data"][@"userinfo"][@"id"];
                SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"id"], @"uid");
                
                [LoginModel shareLogin].username = responseObject[@"data"][@"userinfo"][@"username"];
                SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"username"], @"username");
                
                [self.navigationController popViewControllerAnimated:YES];
                
            }else if ([responseObject[@"status"] isEqual:@2]) { // 注册/登录成功 完善资料
                
                PersonModel *model = [PersonModel yy_modelWithJSON:responseObject[@"data"][@"userinfo"]];
                [InfoCache archiveObject:model toFile:Person];
                
                [LoginModel shareLogin].token = responseObject[@"data"][@"token"];
                SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"token"], @"token");
                
                [LoginModel shareLogin].role = responseObject[@"data"][@"userinfo"][@"role_id"];
                SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"role_id"], @"role");
                
                [LoginModel shareLogin].uid = responseObject[@"data"][@"userinfo"][@"id"];
                SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"id"], @"uid");
                
                [LoginModel shareLogin].username = responseObject[@"data"][@"userinfo"][@"username"];
                SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"username"], @"username");
                
                //            [LoginModel shareLogin].name = responseObject[@"data"][@"userinfo"][@"name"];
                SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"name"], @"name");
                
                YYEMoreInfoViewController *infoVC = [[YYEMoreInfoViewController alloc]init];
                [self.navigationController pushViewController:infoVC animated:YES];
                
            } else if ([responseObject[@"status"] isEqual:@4]) {
                
                YYEBindPhoneViewController *vc = [[YYEBindPhoneViewController alloc]init];
                vc.openid = resp.uid;
                vc.iconurl = resp.iconurl;
                vc.name = resp.name;
                vc.sex = resp.unionGender;
                [self.navigationController pushViewController:vc animated:YES];
                
                if (platformType == UMSocialPlatformType_QQ) {
                    
                    vc.type = @"qq";
                    
                }
                else {
                    vc.type = @"weixin";

                }
                
            }
            [SVProgressHUD showWithStatus:responseObject[@"message"]];
            [SVProgressHUD dismiss];
            
        } faliure:^(id error) {
            
            NSLog(@"请求失败");
            [SVProgressHUD dismiss];
            
        }];
    }];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    NSString *username = [LoginModel shareLogin].username;
    self.phoneTF.text = username;


}

- (void)loginClicked {
    
    NSDictionary *dic = @{
                          @"verify":self.veriTF.text,
                          @"username":self.phoneTF.text
                          };
    
    [AFNHelper post:LoginApi parameters:dic success:^(id responseObject) {
        

        
//        NSLog(@"%@",responseObject);
        if ([responseObject[@"status"] isEqual:@0]) { // 注册/登录失败
            
            NSLog(@"登录失败");
            
        }else if ([responseObject[@"status"] isEqual:@1]) { // 登录成功
            
            PersonModel *model = [PersonModel yy_modelWithJSON:responseObject[@"data"][@"userinfo"]];
            [InfoCache archiveObject:model toFile:Person];
            
            [LoginModel shareLogin].token = responseObject[@"data"][@"token"];
            SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"token"], @"token");
            
            [LoginModel shareLogin].role = responseObject[@"data"][@"userinfo"][@"role_id"];
            SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"role_id"], @"role");
            
            [LoginModel shareLogin].uid = responseObject[@"data"][@"userinfo"][@"id"];
            SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"id"], @"uid");
            
            [LoginModel shareLogin].username = responseObject[@"data"][@"userinfo"][@"username"];
            SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"username"], @"username");
            
//            [self.navigationController popViewControllerAnimated:YES];
            [self.navigationController popToRootViewControllerAnimated:YES];

        }else if ([responseObject[@"status"] isEqual:@2]) { // 注册/登录成功 完善资料
            
            PersonModel *model = [PersonModel yy_modelWithJSON:responseObject[@"data"][@"userinfo"]];
            [InfoCache archiveObject:model toFile:Person];
            
            [LoginModel shareLogin].token = responseObject[@"data"][@"token"];
            SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"token"], @"token");
            
            [LoginModel shareLogin].role = responseObject[@"data"][@"userinfo"][@"role_id"];
            SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"role_id"], @"role");
            
            [LoginModel shareLogin].uid = responseObject[@"data"][@"userinfo"][@"id"];
            SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"id"], @"uid");
            
            [LoginModel shareLogin].username = responseObject[@"data"][@"userinfo"][@"username"];
            SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"username"], @"username");
            
//            [LoginModel shareLogin].name = responseObject[@"data"][@"userinfo"][@"name"];
            SAVEDATAINUSERDEFAULT(responseObject[@"data"][@"userinfo"][@"name"], @"name");
            
            YYEMoreInfoViewController *infoVC = [[YYEMoreInfoViewController alloc]init];
            [self.navigationController pushViewController:infoVC animated:YES];
            
        }
        
    } faliure:^(id error) {
        
        NSLog(@"请求失败");
        
    }];
    
//    YYEBindPhoneViewController *bindVC = [[YYEBindPhoneViewController alloc]init];
//    [self.navigationController pushViewController:bindVC animated:YES];
    
}

#pragma mark-验证码通知方法
- (void)countDownUpdate:(NSNotification *)noti
{
    NSString *identifier = [noti.userInfo objectForKey:@"CountDownIdentifier"];
    if ([identifier isEqualToString:kCountDownForVerifyCode]) {
        NSNumber *n = [noti.userInfo objectForKey:@"SecondsCountDown"];
        
        [self performSelectorOnMainThread:@selector(updateVerifyCodeCountDown:) withObject:n waitUntilDone:YES];
    }
}

- (void)updateVerifyCodeCountDown:(NSNumber *)num {
    
    if ([num integerValue] == 0){
        
        [self.countDownButton setTitle:@"重新获取" forState:UIControlStateNormal];
        self.countDownButton.userInteractionEnabled = YES;
        [self.countDownButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        
    } else {
        [self.countDownButton setTitle:[NSString stringWithFormat:@"已发送(%@)",num] forState:UIControlStateNormal];
        self.countDownButton.userInteractionEnabled = NO;
        [self.countDownButton setTitleColor:[UIColor colorWithHexString:@"#efefef"] forState:UIControlStateNormal];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
